//
//  BDYouhuiHomeViewController.m
//  BeidouMall
//
//  Created by qie on 16/8/2.
//  Copyright © 2016年 qie. All rights reserved.
//

#import "BDYouhuiHomeViewController.h"
#import "BDGoodDetailViewController.h"

#define kPageSize 5

@interface BDYouhuiHomeViewController () <UITableViewDelegate,UITableViewDataSource>

{
    NSMutableArray *_dataList;
    NSInteger _curPage;
    
    NSInteger _selectedIndex;
}

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *firstButton;
@property (weak, nonatomic) IBOutlet UIView *topContainerview;
@property (weak, nonatomic) IBOutlet UILabel *topFirstLabel;
@property (weak, nonatomic) IBOutlet UILabel *topSecondLabel;
@property (weak, nonatomic) IBOutlet UILabel *topThirdLabel;

@end

@implementation BDYouhuiHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"优惠券";
   
    // 自定义tableview刷新的头部和尾部
    [self setTableViewHeader];
    [self setTableViewFooter];
    _dataList = [[NSMutableArray alloc] init];
    _curPage = 0;
    [self.tableView.mj_header beginRefreshing];

    if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"zang"]) {
        self.topFirstLabel.font = [UIFont fontWithName:@"Bzdbt" size:8.0];
        self.topSecondLabel.font = [UIFont fontWithName:@"Bzdbt" size:8.0];
        self.topThirdLabel.font = [UIFont fontWithName:@"Bzdbt" size:8.0];
    }
    
    // 刷新title数量
    [self titleReloadData:1];
    [self titleReloadData:2];
    
    _selectedIndex = 0;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Private method

- (void)titleReloadData:(NSInteger) index {
    NSString *url;
    if (index == 0) {
        url = [NSString stringWithFormat:@"%@%@?currentPage=%ld&pageSize=%d&userId=%@&status=UNUSED&overdue=%@",
               [BDNetworking shareInstance].baseUrl,
               Youhui_Query,
               (long)1,
               kPageSize,
               [BDAccountManagerModel shareInstance].userId,
               @"no"];
    } else if (index == 1) {
        url = [NSString stringWithFormat:@"%@%@?currentPage=%ld&pageSize=%d&userId=%@&status=UNUSED&overdue=%@",
               [BDNetworking shareInstance].baseUrl,
               Youhui_Query,
               (long)1,
               kPageSize,
               [BDAccountManagerModel shareInstance].userId,
               @"yes"];
    } else if (index == 2) {
        url = [NSString stringWithFormat:@"%@%@?currentPage=%ld&pageSize=%d&userId=%@&status=USED",
               [BDNetworking shareInstance].baseUrl,
               Youhui_Query,
               (long)1,
               kPageSize,
               [BDAccountManagerModel shareInstance].userId];
    }
    [[BDNetworking shareInstance] postWithUrl:url sid:nil method:@"GET" parameters:nil completionHandler:^(NSObject *results, NSError *error) {
        if (error != nil) {
            NSLog(@"优惠券列表title刷新失败:%@",error);
        } else {
            if ([results isKindOfClass:[NSDictionary class]]) {
                NSDictionary *resultDic = (NSDictionary *)results;
                NSString *num = resultDic[@"number"];
                if (![num isEqual:[NSNull null]]) {
                    if (index == 1) {
                        _topSecondLabel.text = [NSString stringWithFormat:@"已过期(%@)",num];
                    } else if (index == 2) {
                        _topThirdLabel.text = [NSString stringWithFormat:@"已使用(%@)",num];
                    }
                }
            }
        }
    }];
}

- (void)reloadData:(id) sender {
    _curPage = sender == self ? 1 : _curPage + 1;
    if (_curPage == 1) {// 消除没有更多数据的状态
        [_tableView.mj_footer resetNoMoreData];
        _tableView.mj_footer.hidden = NO;
    }
    // 未使用 未过期
    // 未使用 已过期
    // 已使用
    NSString *url;
    if (_selectedIndex == 0) {
        url = [NSString stringWithFormat:@"%@%@?currentPage=%ld&pageSize=%d&userId=%@&status=UNUSED&overdue=%@",
               [BDNetworking shareInstance].baseUrl,
               Youhui_Query,
               (long)_curPage,
               kPageSize,
               [BDAccountManagerModel shareInstance].userId,
               @"no"];
    } else if (_selectedIndex == 1) {
        url = [NSString stringWithFormat:@"%@%@?currentPage=%ld&pageSize=%d&userId=%@&status=UNUSED&overdue=%@",
               [BDNetworking shareInstance].baseUrl,
               Youhui_Query,
               (long)_curPage,
               kPageSize,
               [BDAccountManagerModel shareInstance].userId,
               @"yes"];
    } else if (_selectedIndex == 2) {
        url = [NSString stringWithFormat:@"%@%@?currentPage=%ld&pageSize=%d&userId=%@&status=USED",
               [BDNetworking shareInstance].baseUrl,
               Youhui_Query,
               (long)_curPage,
               kPageSize,
               [BDAccountManagerModel shareInstance].userId];
    }
    
    MBProgressHUD *hud;
    
    [[BDNetworking shareInstance] postWithUrl:url sid:nil method:@"GET" parameters:nil completionHandler:^(NSObject *results, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([_tableView.mj_header isRefreshing]) {
                [_tableView.mj_header endRefreshing];
            }
            if ([_tableView.mj_footer isRefreshing]) {
                [_tableView.mj_footer endRefreshing];
            }
        });
        if (error != nil) {
            NSLog(@"优惠券列表获取失败:%@",error);
            dispatch_async(dispatch_get_main_queue(), ^{
                _tableView.mj_footer.hidden = YES;
            });
            if (hud) {
                hud.labelText = @"优惠券列表获取失败";
                [hud hideAfterDelay:0.5];
            } else {
                [MBProgressHUD showToast:self.view withText:@"优惠券列表获取失败"];
            }
        } else {
            if (hud) {
                [hud hideAfterDelay:0.5];
            }
            if ([results isKindOfClass:[NSDictionary class]]) {
                NSLog(@"results = %@",results);
                NSDictionary *resultDic = (NSDictionary *)results;
                
                NSString *num = resultDic[@"number"];
                if (![num isEqual:[NSNull null]]) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (_selectedIndex == 0) {
                            _topFirstLabel.text = [NSString stringWithFormat:@"未使用(%@)",num];
                        } else if (_selectedIndex == 1) {
                            _topSecondLabel.text = [NSString stringWithFormat:@"已过期(%@)",num];
                        } else if (_selectedIndex == 2) {
                            _topThirdLabel.text = [NSString stringWithFormat:@"已使用(%@)",num];
                        }
                    });
                }
                
                NSArray *resultList = resultDic[@"objects"];
                if ([resultList count] > 0) {
                    if ([resultList count] < kPageSize) {// 数据不够分页,显示没有更多了
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [_tableView.mj_footer endRefreshingWithNoMoreData];
                        });
                    }
                    if (sender == self) {
                        [_dataList removeAllObjects];
                    }
                    [_dataList addObjectsFromArray:resultList];
                } else {
                    if (_curPage > 1) { // 分页引起的刷新
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [_tableView.mj_footer endRefreshingWithNoMoreData];
                            _tableView.mj_footer.hidden = YES;
                        });
                    } else { // 刷新之前的数据应该清零
                        [_dataList removeAllObjects];
                    }
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    [_tableView reloadData];
                });
            }
        }
    }];
}

- (void)setTableViewHeader {
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self reloadData:self];
    }];
    if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"zang"]) {
        header.stateLabel.font = [UIFont fontWithName:@"Bzdbt" size:9.0];
    }
    
    [header setTitle:NSLocalizedString(@"Pull down to refresh", nil) forState:MJRefreshStateIdle];
    [header setTitle:NSLocalizedString(@"Release to refresh", nil) forState:MJRefreshStatePulling];
    [header setTitle:NSLocalizedString(@"Loading ...", nil) forState:MJRefreshStateRefreshing];
    // 隐藏时间
    header.lastUpdatedTimeLabel.hidden = YES;
    
    _tableView.mj_header = header;
}

- (void)setTableViewFooter {
    _tableView.mj_footer = [MJDIYBackFooter footerWithRefreshingTarget:self refreshingAction:@selector(reloadData:)];
}

#pragma mark tableView dataSrouce

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _dataList.count > 0 ? _dataList.count : 1 ;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (_dataList.count > 0) {
        static NSString *cellStr = @"comCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
        
        UILabel *titleLabel = (UILabel *)[cell viewWithTag:101];
        NSString *type = _dataList[indexPath.section][@"couponRange"];
        if (![type isEqual:[NSNull null]]) {
            if ([type isEqualToString:@"COMMODITY"]) {
                titleLabel.text = @"商品优惠券";
            } else {
                titleLabel.text = @"优惠券";
            }
        }
        
        UILabel *nameLabel = (UILabel *)[cell viewWithTag:102];
        NSString *name = _dataList[indexPath.section][@"name"];
        if (![name isEqual:[NSNull null]]) {
            nameLabel.text = name;
        }
        
        UILabel *dateLabel = (UILabel *)[cell viewWithTag:103];
        NSNumber *start_time = _dataList[indexPath.section][@"startTime"];
        NSNumber *end_time = _dataList[indexPath.section][@"endTime"];
        
        NSString *startTimeStr = [NSString converToDateString:[start_time doubleValue] / 1000 formatter:@"yyyy.MM.dd"];
        NSString *endTimeStr = [NSString converToDateString:[end_time doubleValue] / 1000 formatter:@"yyyy.MM.dd"];
        dateLabel.text = [NSString stringWithFormat:@"使用期限%@-%@",startTimeStr,endTimeStr];
        
        return cell;
    } else {
        static NSString *cellStr = @"noCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
        return cell;
    }
    
}

#pragma mark tableView delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    _tableView.scrollEnabled = _dataList.count > 0 ? YES : NO;
    return _dataList.count > 0 ? 112.0 : kScreen_Height - 104.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 11.0;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, 11.0)];
    header.backgroundColor = RGBColor(238, 238, 238);
    return header;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return NO;
//    return _dataList.count > 0 ? YES : NO;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSLog(@"delete");
        [_dataList removeObjectAtIndex:indexPath.section];
        [_tableView reloadData];
    }
}

- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 添加一个删除按钮
    UITableViewRowAction *deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删 除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        NSLog(@"点击了删除");
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        UIView *view = [cell viewWithTag:201];
        view.hidden = YES;
        [_dataList removeObjectAtIndex:indexPath.section];
        [_tableView reloadData];
    }];
//    deleteRowAction.backgroundColor = RGBColor(238, 238, 238);
    
    // 将设置好的按钮放到数组中返回
    return @[deleteRowAction];
}

- (void)tableView:(UITableView *)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    UIView *view = [cell viewWithTag:201];
    view.hidden = NO;
}

- (void)tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
    dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 0.5);
    dispatch_after(time, dispatch_get_main_queue(), ^{
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        UIView *view = [cell viewWithTag:201];
        view.hidden = YES;
    });
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_dataList.count > 0) {
        NSString *commodityId = _dataList[indexPath.section][@"commodityId"];
        if ([commodityId isEqual:[NSNull null]] ||
            commodityId != nil) {
            UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"SecondStoryboard" bundle:[NSBundle mainBundle]];
            BDGoodDetailViewController *detailVC = [stroyboard instantiateViewControllerWithIdentifier:@"goodDetailStoryboardID"];
            detailVC.commodityId = commodityId;
            detailVC.isFromHomePage = YES;
            [self.navigationController pushViewController:detailVC animated:YES];
        }
    }
}

#pragma mark - IBActions

- (IBAction)classButtonPressed:(UIButton *)sender {
    NSInteger index = sender.tag - 400;
    NSInteger count = 0;
    UIView *superView = sender.superview;
    UIView *containerView = superView.superview;
    
    for (UIView *view in containerView.subviews) {
        count++;
        if (count == index) {
            UILabel *label = [view viewWithTag:100 + index];
            label.textColor = RGBColor(215, 19, 33);
            UIImageView *imageView = [view viewWithTag:200 + index];
            imageView.hidden = NO;
            UIView *line = [view viewWithTag:300 + index];
            line.hidden = NO;
        } else {
            UILabel *label = [view viewWithTag:100 + count];
            label.textColor = RGBColor(102, 102, 102);
            UIImageView *imageView = [view viewWithTag:200 + count];
            imageView.hidden = YES;
            UIView *line = [view viewWithTag:300 + count];
            line.hidden = YES;
        }
    }
    sender.selected = !sender.selected;
    
    if (sender.tag == 401) {// 销量
        _selectedIndex = 0;
    } else if (sender.tag == 402) {//价格
        _selectedIndex = 1;
    } else if (sender.tag == 403) {// 评分
        _selectedIndex = 2;
    }
    [self reloadData:self];
}

#pragma mark - IBActions

- (IBAction)dismissButtonPressed:(UIBarButtonItem *)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
